package com.kuang.bq;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @program: juc
 * @description: 同步队列，和其他的blockingqueue不一样，SynchronousQueue不存储元素，put了一个元素，必须从里面先take取出来，否则不能再put进去值！
 * @author: 陈恩涛
 * @create: 2021-03-09 17:35
 **/
public class SynchronousQueueDemo {

    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new SynchronousQueue<String>(); //同步队列

        new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                System.out.println(Thread.currentThread().getName()+" put "+i);
                try {
                    blockingQueue.put(""+i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"T1").start();

        new Thread(() -> {

            try {
                for (int i = 1; i <= 3; i++) {
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+" take "+blockingQueue.take());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();
    }
}
